<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/greenwood.gitee.io/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/greenwood.gitee.io/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/greenwood.gitee.io/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/greenwood.gitee.io/images/logo.svg" color="#222">

<link rel="stylesheet" href="/greenwood.gitee.io/css/main.css">


<link rel="stylesheet" href="/greenwood.gitee.io/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/greenwood.gitee.io/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="问题引入给定一个员工表和一个部门表，查找所有的已分配部门的员工信息(name + 部门编号)，如果暂时没有分配部门，则为空">
<meta property="og:type" content="article">
<meta property="og:title" content="Mysql的Left Join操作">
<meta property="og:url" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/15/mysql%E7%9A%84leftjoin%E5%92%8Con%E6%93%8D%E4%BD%9C/index.html">
<meta property="og:site_name" content="我看刑">
<meta property="og:description" content="问题引入给定一个员工表和一个部门表，查找所有的已分配部门的员工信息(name + 部门编号)，如果暂时没有分配部门，则为空">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/15/mysql%E7%9A%84leftjoin%E5%92%8Con%E6%93%8D%E4%BD%9C/1.jpg">
<meta property="og:image" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/15/mysql%E7%9A%84leftjoin%E5%92%8Con%E6%93%8D%E4%BD%9C/2.jpg">
<meta property="og:image" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/15/mysql%E7%9A%84leftjoin%E5%92%8Con%E6%93%8D%E4%BD%9C/res.jpg">
<meta property="article:published_time" content="2021-10-15T06:40:00.000Z">
<meta property="article:modified_time" content="2021-10-14T23:56:13.462Z">
<meta property="article:author" content="Dybala">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="MySql">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/15/mysql%E7%9A%84leftjoin%E5%92%8Con%E6%93%8D%E4%BD%9C/1.jpg">

<link rel="canonical" href="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/15/mysql%E7%9A%84leftjoin%E5%92%8Con%E6%93%8D%E4%BD%9C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Mysql的Left Join操作 | 我看刑</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/greenwood.gitee.io/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">我看刑</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/greenwood.gitee.io/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/greenwood.gitee.io/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/greenwood.gitee.io/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/greenwood.gitee.io/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/greenwood.gitee.io/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/greenwood-drgon/greenwood.gitee.io/2021/10/15/mysql%E7%9A%84leftjoin%E5%92%8Con%E6%93%8D%E4%BD%9C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/greenwood.gitee.io/images/avatar.gif">
      <meta itemprop="name" content="Dybala">
      <meta itemprop="description" content="日子越来越有判头了">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="我看刑">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Mysql的Left Join操作
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-10-15 14:40:00 / 修改时间：07:56:13" itemprop="dateCreated datePublished" datetime="2021-10-15T14:40:00+08:00">2021-10-15</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/greenwood.gitee.io/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="问题引入"><a href="#问题引入" class="headerlink" title="问题引入"></a>问题引入</h1><p>给定一个员工表和一个部门表，查找所有的已分配部门的员工信息(name + 部门编号)，如果暂时没有分配部门，则为空<br><span id="more"></span><br><a target="_blank" rel="noopener" href="https://www.nowcoder.com/practice/dbfafafb2ee2482aa390645abd4463bf?tpId=82&amp;&amp;tqId=29757&amp;rp=1&amp;ru=/ta/sql&amp;qru=/ta/sql/question-ranking">原题连接</a><br>员工表：<br><img src="1.jpg" alt=""><br>部门表：<br><img src="2.jpg" alt=""><br>查询结果：<br><img src="res.jpg" alt=""></p>
<h2 id="1-答案"><a href="#1-答案" class="headerlink" title="1. 答案"></a>1. 答案</h2><p>在本题中，需要<strong>完整保留员工表的所有行</strong>，所以想到left join，具体的sql语句如下：<br><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">select</span> last_name,first_name,dept_no</span><br><span class="line"><span class="keyword">from</span> employees a <span class="keyword">left</span> <span class="keyword">join</span> dept_emp b </span><br><span class="line"><span class="keyword">on</span> a.emp_no<span class="operator">=</span>b.emp_no;</span><br></pre></td></tr></table></figure></p>
<h2 id="2-关于left-join"><a href="#2-关于left-join" class="headerlink" title="2. 关于left join"></a>2. 关于left join</h2><p>LEFT JOIN子句允许您从匹配的左右表中查询选择行记录，连接左表(a)中的<strong>所有行</strong>，即使在右表(b)中找不到匹配的行也显示出来，但使用NULL值代替。</p>
<h3 id="2-1-执行原理"><a href="#2-1-执行原理" class="headerlink" title="2.1 执行原理"></a>2.1 执行原理</h3><p>mysql 对于left join的采用类似嵌套循环的方式来进行从处理，以下面的语句为例：<br><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">SELECT</span> <span class="operator">*</span> <span class="keyword">FROM</span> LT <span class="keyword">LEFT</span> <span class="keyword">JOIN</span> RT <span class="keyword">ON</span> P1(LT,RT)) <span class="keyword">WHERE</span> P2(LT,RT)</span><br></pre></td></tr></table></figure><br>其中P1是on过滤条件，缺失则认为是TRUE，P2是where过滤条件，缺失也认为是TRUE，该语句的执行逻辑可以描述为：<br><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">FOR each row lt in LT &#123;// 遍历左表的每一行</span><br><span class="line">  BOOL b = FALSE;</span><br><span class="line">  FOR each row rt in RT such that P1(lt, rt) &#123;// 遍历右表每一行，找到满足join条件的行</span><br><span class="line">    IF P2(lt, rt) &#123;//满足 where 过滤条件</span><br><span class="line">      t:=lt||rt;//合并行，输出该行</span><br><span class="line">    &#125;</span><br><span class="line">    b=TRUE;// lt在RT中有对应的行</span><br><span class="line">  &#125;</span><br><span class="line">  IF (!b) &#123; // 遍历完RT，发现lt在RT中没有有对应的行，则尝试用null补一行</span><br><span class="line">    IF P2(lt,NULL) &#123;// 补上null后满足 where 过滤条件</span><br><span class="line">      t:=lt||NULL; // 输出lt和null补上的行</span><br><span class="line">    &#125;         </span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>如果想对右表进行限制，则一定要在on条件中进行，若在where中进行则可能导致数据缺失，导致左表在右表中无匹配行的行在最终结果中不出现，违背了我们对left join的理解。因为对左表无右表匹配行的行而言，遍历右表后b=FALSE,所以会尝试用NULL补齐右表，但是此时我们的P2对右表行进行了限制，NULL若不满足P2(NULL一般都不会满足限制条件，除非IS NULL这种)，则不会加入最终的结果中，导致结果缺失。</li>
<li>如果没有where条件，无论on条件对左表进行怎样的限制，左表的每一行都至少会有一行的合成结果，对左表行而言，若右表若没有对应的行，则右表遍历结束后b=FALSE，会用一行NULL来生成数据，而这个数据是多余的。所以对左表进行过滤必须用where。</li>
<li>WHERE的执行在ON之后，也就是说on用于确定怎么连接两个表，where用于筛选新表。</li>
<li>如果不指定on(用ON 1=1 代替)，则生成笛卡儿积。</li>
</ul>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/greenwood.gitee.io/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="tag"># 数据库</a>
              <a href="/greenwood.gitee.io/tags/MySql/" rel="tag"># MySql</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/greenwood.gitee.io/2021/10/13/%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/" rel="prev" title="工厂模式">
      <i class="fa fa-chevron-left"></i> 工厂模式
    </a></div>
      <div class="post-nav-item">
    <a href="/greenwood.gitee.io/2021/10/15/Springbootapplication/" rel="next" title="Springbootapplication">
      Springbootapplication <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%97%AE%E9%A2%98%E5%BC%95%E5%85%A5"><span class="nav-number">1.</span> <span class="nav-text">问题引入</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E7%AD%94%E6%A1%88"><span class="nav-number">1.1.</span> <span class="nav-text">1. 答案</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E5%85%B3%E4%BA%8Eleft-join"><span class="nav-number">1.2.</span> <span class="nav-text">2. 关于left join</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E6%89%A7%E8%A1%8C%E5%8E%9F%E7%90%86"><span class="nav-number">1.2.1.</span> <span class="nav-text">2.1 执行原理</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Dybala</p>
  <div class="site-description" itemprop="description">日子越来越有判头了</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/greenwood.gitee.io/archives/">
        
          <span class="site-state-item-count">22</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/greenwood.gitee.io/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/greenwood.gitee.io/tags/">
          
        <span class="site-state-item-count">22</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Dybala</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/greenwood.gitee.io/lib/anime.min.js"></script>
  <script src="/greenwood.gitee.io/lib/velocity/velocity.min.js"></script>
  <script src="/greenwood.gitee.io/lib/velocity/velocity.ui.min.js"></script>

<script src="/greenwood.gitee.io/js/utils.js"></script>

<script src="/greenwood.gitee.io/js/motion.js"></script>


<script src="/greenwood.gitee.io/js/schemes/pisces.js"></script>


<script src="/greenwood.gitee.io/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
